const fs = require('fs')
const path = require('path')
const mkdirp = require('mkdirp')
const program = require('commander')
const superagent = require('superagent')
const {
  resolve,
  prefix,
  getToken
} = require('./utils')

module.exports = async (name, command) => {
  const token = getToken()

  if (!token) return
  const res = await superagent
    .post('/Site5ug/Create', {
      ...token,
      command: command,
      parameter: name
    })
    .use(prefix)

  const {
    status,
    result
  } = res.body

  if (status !== 1) {
    console.info('错误' + res.body.message)
    return
  }

  await Promise.all(result.map(file => new Promise((res, rej) => {
    const filePath = resolve(file.path)
    const dirPath = path.dirname(filePath)
    const compName = filePath.replace(`${dirPath}${path.sep}`, '')

    mkdirp(dirPath, function (err) {
      if (err && program.debug) {
        console.error(err)
        return
      }
      fs.writeFile(filePath, file.content, err => {
        if (err) {
          rej(err)
          if (program.debug) console.error(err)
          console.log(`文件 ${compName} 创建失败,路径 ${filePath}`)
          return
        }
        res()
        console.log(`文件 ${compName} 创建成功,路径 ${filePath}`)
      })
    })
  })))

  require('../lib/main')()
}
